package org.usmile.algorithms.leetcode.middle;

import java.util.Arrays;

/**
 * 179. 最大数
 * <p>
 * 给定一组非负整数 nums，重新排列每个数的顺序（每个数不可拆分）使之组成一个最大的整数。
 * <p>
 * 注意：输出结果可能非常大，所以你需要返回一个字符串而不是整数。
 * <p>
 * 示例 1：
 * <p>
 * 输入：nums = [10,2]
 * 输出："210"
 * <p>
 * 示例 2：
 * <p>
 * 输入：nums = [3,30,34,5,9]
 * 输出："9534330"
 * <p>
 * 提示：
 * <p>
 * 1 <= nums.length <= 100
 * 0 <= nums[i] <= 109
 */
public class _0179 {
}

class _0179_Solution1 {
    public String largestNumber(int[] nums) {
        if (nums == null || nums.length == 0) {
            return "0";
        }

        String[] stringNums = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            stringNums[i] = nums[i] + "";
        }

        Arrays.sort(stringNums, (o1, o2) -> {
            String x = o1 + o2;
            String y = o2 + o1;
            return y.compareTo(x);
        });

        if ("0".equals(stringNums[0])) {
            return "0";
        }

        StringBuilder sb = new StringBuilder();
        for (String num : stringNums) {
            sb.append(num);
        }

        return sb.toString();
    }
}

class _0179_Solution2 {
    public String largestNumber(int[] nums) {
        if (nums == null || nums.length == 0) {
            return "0";
        }

        quickSort(nums, 0 , nums.length - 1);
        if (nums[0] == 0) {
            return "0";
        }

        StringBuilder sb = new StringBuilder();
        for (int num : nums) {
            sb.append(num);
        }

        return sb.toString();
    }

    private void quickSort(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }
        int p = partition(nums, left, right);

        quickSort(nums, left, p -1);
        quickSort(nums, p + 1, right);
    }

    private int partition(int[] nums, int left, int right) {
        int pivot = nums[right];
        int i = left;
        int great = left;
        while (i < right) {
            String x = nums[i] + "" + pivot;
            String y = pivot + "" + nums[i];
            if (x.compareTo(y) > 0) {
                if (great != i) {
                    swap(nums, great, i);
                }
                great++;
            }

            i++;
        }

        swap(nums, great, right);

        return great;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[j];
        nums[j] = nums[i];
        nums[i] = temp;
    }
}